import { Col } from "./col";
import { Config } from "./config";
import { Tooler } from "./tooler"

export class Core {
  cols = [];
  connData = {};
  ostIndex = 0;
  connCards = [];
  smlt = [1, 2, 3, 5];
  running = false;

  constructor() {
    // Config.init();
    // for (let i = 0; i < Config.CARDS_PER_ROW; i++) {
    //   this.cols.push(new Col(i))
    // }
    // this.randomCards(Config.CARDS_PER_COL)

    // this.play()
  }

  init(w, h) {
    Config.init(w, h)
    for (let i = 0; i < Config.CARDS_PER_ROW; i++) {
      this.cols.push(new Col(i))
    }
    this.randomCards(Config.CARDS_PER_COL)
  }

  randomCards(rows) {
    this.cols.forEach(col => col.randomCards(rows))
  }

  async play() {
    this.ostIndex = 0;
    this.running = true;
    console.log("----开始")
    const conn = await this.loadData();
    this.connData = conn.data;
    const otherNum = 14;//补充个数
    const ost = this.connData.dt.ost;
    this.smlt = this.connData.dt.smlt;
    const aimList = Array(5).fill([]);
    ost.forEach(item => {
      const ary = Tooler.groupArrayBySeven(item);
      ary.forEach((temp, i) => {
        aimList[i] = temp.concat(aimList[i]);
      })
    })

    //真实的牌型数据后面添加补充个数，做滚动效果
    aimList.forEach(item => {
      for (let i = 0; i < otherNum; i++) {
        item.push(Tooler.getRandomInt(0, 10))
      }
    })

    //初始化牌型
    this.cols.forEach((col, i) => col.addAimCards(aimList[i]));
    //设置位置和移动距离以及时间
    this.cols.forEach((col, i) => col.initPosition(21, i));

    await this.dropDown(true);
    this.running = false;
    console.log("----结束")
  }

  async dropDown(isScroll) {
    // console.log("ostIndex", this.ostIndex)
    console.log("开始下落")

    //播放滚动动画
    this.cols.forEach(col => col.play());

    //等待动画结束
    if(isScroll){
      await Tooler.sleep(Config.SCROLL_TIMER + Config.GAP_TIMER * this.cols.length);
    }
    else{
      await Tooler.sleep(Config.DROP_DOWN_TIMER + 300);
    }
    console.log("下落动画结束")

    //更新索引
    this.cols.forEach(col => col.updateOrder());
    console.log("更新索引")

    await Tooler.sleep(100)

    //获取连接的牌
    this.connCards = this.getWillRemoveItems();

    if (this.connCards.length == 0) {
      this.cols.forEach(col => col.removeOutside());
      this.ostIndex = 0;
      return
    }

    //设置选中状态
    this.connCards.forEach(card => card.choose(true));
    console.log("选中连接牌")

    //等待连接动画结束
    await Tooler.sleep(Config.CHOOSE_TIMER);

    //根据移除元素计算下落距离
    this.cols.forEach(col => {
      col.fixPosition(this.connCards)
      col.removeBottom()
      col.removeConn(this.connCards)
    })

    this.ostIndex++;

    await this.dropDown(false);
  }

  getWillRemoveItems() {
    const ary = [];
    const temp = this.connData.dt.cn.conn[this.ostIndex];

    let ids = [];
    for (let i in temp) {
      ids = ids.concat(temp[i]);
    }
    // console.log("remove ids ", ids);

    this.cols.forEach(col => {
      col.cards.forEach(card => {
        if (ids.includes(card.order)) {
          ary.push(card);
        }
      })
    })
    // console.log("remove cards ", ary);
    return ary;

    // for (let i in temp) {
    //   console.log("删除idx", temp[i])
    //   const ary = temp[i].map(item => {
    //     return this.curList.find(val => val.idx == item)
    //   })
    //   return ary
    // }
    // return []
  }

  async loadData() {
    return new Promise(resolve => {
      fetch(Config.DATA_URL)
        .then(response => {
          return response.json();
        })
        .then(data => {
          // console.log(data);
          resolve(data)
        })
        .catch(error => {
          // console.error('There was a problem fetching the data:', error);
          resolve(null)
        });
    })

  }
}